import { useImmer } from "use-immer";

interface ListDataType {
  id: number;
  title: string;
  seen: boolean;
}

interface ItemListProps {
  artworks: ListDataType[];
  onToggle: (id: number, nextSeen: boolean) => void;
}

const initialList: ListDataType[] = [
  { id: 0, title: "吃早饭", seen: false },
  { id: 1, title: "上班", seen: false },
  { id: 2, title: "下班", seen: true }
];

function ItemList({ artworks, onToggle }: ItemListProps) {
  return (
    <ul>
      {artworks.map(artwork => (
        <li key={artwork.id}>
          <label>
            <input type="checkbox" checked={artwork.seen} onChange={e => onToggle(artwork.id, e.target.checked)} />
            {artwork.title}
          </label>
        </li>
      ))}
    </ul>
  );
}

function BucketList() {
  const [list, updateList] = useImmer(initialList);

  function handleOnToggle(artworkId: number, nextSeen: boolean) {
    updateList(draft => {
      const artwork = draft.find(a => a.id === artworkId);
      if (artwork) {
        artwork.seen = nextSeen;
      }
    });
  }

  return (
    <>
      <h1>日常待办项</h1>
      <h2>打勾表示已完成</h2>
      <ItemList artworks={list} onToggle={handleOnToggle} />
    </>
  );
}

export default BucketList;
